﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Linq.Expressions;

namespace CommonPatterns.MVVM
{
    public abstract class BindableElement : INotifyPropertyChanged
    {
        #region Fields
        // this dictionnary contains all the notification instances of notifiant elements (properties, commands, etc.)
        private IDictionary<string, PropertyChangedEventArgs> propertyChangedEventArgsDic;
        #endregion

        #region Consructor
        public BindableElement()
        {
            propertyChangedEventArgsDic = new Dictionary<string, PropertyChangedEventArgs>();
        }
        #endregion

        #region Events
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region internal Helpers
        /// <summary>
        /// This method raises PropertyChanged notification considering memory optimisation issues: 
        /// notification objects are cached to void the intervention of the GC
        /// </summary>
        /// <param name="propertyName"></param>
        private void RaisePropertyChanged(string propertyName)
        {
            var handlers = PropertyChanged;
            if (handlers != null)
            {
                PropertyChangedEventArgs propertyChangedEventArgs = null;
                if (!propertyChangedEventArgsDic.ContainsKey(propertyName))
                    propertyChangedEventArgsDic[propertyName] = new PropertyChangedEventArgs(propertyName);
                propertyChangedEventArgs = propertyChangedEventArgsDic[propertyName];
                handlers(this, propertyChangedEventArgs);
            }
        }

        /// <summary>
        /// This method raises a property change notification for member expressions in a type-safe manner. 
        /// provides compile-time type safety and refactoring support if you rename a property
        /// <remarks>
        /// BE AWARE !! Using a lambda expression in this way involves a small performance cost because
        /// the lambda expression has to be evaluated for each call
        /// </remarks>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyExpression"></param>
        protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            var body = propertyExpression.Body as System.Linq.Expressions.MemberExpression;
            if (body != null)
                RaisePropertyChanged(body.Member.Name);
        }

        #endregion
    }
}
